package cn.ac.jaas.ljx.mybatis.Service;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.ac.jaas.ljx.mybatis.MySqlSessionFactory;
import cn.ac.jaas.ljx.mybatis.dao.StudentDao;
import cn.ac.jaas.ljx.mybatis.model.Student;

public class StudentService {

    @SuppressWarnings("unused")
    private Logger logger = LoggerFactory.getLogger(StudentService.class);
    
    private StudentDao studentDao;
    private SqlSession sqlSession;
    
    private void init() {
        this.sqlSession = MySqlSessionFactory.openSession();
        this.studentDao = sqlSession.getMapper(StudentDao.class);
    }
    
    public List<Student> findAll() {
        init();
        try {
            return studentDao.findAll();
        } finally {
            sqlSession.close();
        }
        
    }
    
    public int insert(Student student) {
        init();
        try {
            int result= studentDao.insert(student);
            sqlSession.commit();
            return result;
        } finally {
            sqlSession.close();
        }
        
    }
    
    public int delete(int id) {
        init();
        try {
            int result = studentDao.deleteOneById(id);
            sqlSession.commit();
            return result;
        } finally {
            sqlSession.close();
        }
    }
    
    public int update(Student student) {
        init();
        try {
            int result = studentDao.update(student);
            sqlSession.commit();
            return result;
        } finally {
            sqlSession.close();
        }
    }
    
    public Student findOneById(int id) {
        init();
        try {
            return studentDao.findOneById(id);
        } finally {
            sqlSession.close();
        }
    }
    
    public Student findOneWithAddrById(int id) {
        init();
        try {
            return studentDao.findStudentWithAddrById(id);
        } finally {
            sqlSession.close();
        }
    }
}
